YAHOO.namespace("pingmob");
YAHOO.namespace("pingmob.container");

YAHOO.util.Event.onDOMReady(function () {
    YAHOO.pingmob.userList = function () {

        var number_per_page_default = 10;

        var Dom = YAHOO.util.Dom,
            Event = YAHOO.util.Event;

        var myPaginator = new YAHOO.widget.Paginator({
            containers:['users-thread-paging','users-thread-paging_top'],
            rowsPerPage:number_per_page_default,
            previousPageLinkClass:"yui-pg-previous gc-inbox-prev",
            nextPageLinkClass:"yui-pg-next gc-inbox-next"//,
            //template           : "<strong>{CurrentPageReport}</strong> {PreviousPageLink} {NextPageLink}",
            //pageReportTemplate : "{startIndex}-{endIndex} of {totalRecords}"
        });
        var myTableConfig = {
            paginator:myPaginator,
            MSG_EMPTY:messages["js.no.records.found"],
            dynamicData:true,
            initialLoad:false,
            width:'100%'
        };

        var formatDate = function(elCell, oRecord, oColumn, oData) {
            if (oData!=null && oData!="") {
                var oDate = new Date(oData);
                elCell.innerHTML = YAHOO.util.Date.format(oDate, {format:"%Y-%m-%d"});
            }
        };

        var myColumnDefs = [
            {key:"Select", label:"", formatter:"checkbox", className:"table-checkbox"},
            {key:"id", label:"ID", sortable:true},
            {key:"source", label:'来源',sortable:true},
            {key:"username", label:'用户名', sortable:true},
            {key:"fullName", label:'姓名',sortable:true},
            {key:"gender", label:'性别',sortable:true, formatter:function (elCell, oRecord, oColumn, oData) {
                if(oData == "male"){
                    elCell.innerHTML = "男";
                }else{
                    elCell.innerHTML = "女";
                }
            }},
            {key:"birthday", label:'生日',sortable:true, formatter:formatDate},
            {key:"age", label:'年龄',sortable:true},
            {key:"email", label:'邮箱',sortable:true},
            {key:"mobile", label:'手机',sortable:true},
            {key:"phone", label:'座机',sortable:true},
            {key:"deviceInfo", label:'用户设备信息',sortable:true},
            {key:"dateAdded", label:'注册时间',sortable:true, formatter:formatDate},
            {key:"view", label:'星卡详情', className:"table-action", action:'view', formatter:function (elCell) {
                elCell.innerHTML = '<img src="/static/images/edit.gif" title="查看"/>';
                elCell.style.cursor = 'pointer';
            }}//,
/*
            {key:"oauth", label:'Oauth', className:"table-action", action:'oauth', formatter:function (elCell) {
                elCell.innerHTML = '<img src="/static/images/edit.gif" title="Oauth授权"/>';
                elCell.style.cursor = 'pointer';
            }}
*/
        ];
        var usersDataSource = new YAHOO.util.DataSource('/admin/users/json?');
        usersDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
        usersDataSource.responseSchema = {
            resultsList:'records',
            metaFields:{
                totalRecords:'totalRecords',
                paginationRecordOffset:"startIndex",
                paginationRowsPerPage:"pageSize",
                sortKey: "sort",
                sortDir: "dir"
            }
        };
        var usersDataTable = new YAHOO.widget.DataTable("users-thread-list", myColumnDefs, usersDataSource, myTableConfig);

        // Show loading message while page is being rendered
        usersDataTable.showTableMessage(usersDataTable.get("MSG_LOADING"), YAHOO.widget.DataTable.CLASS_LOADING);

        // Add the instances to the YAHOO.example namespace for inspection
        YAHOO.pingmob.BHMIntegration_files = {
            myPaginator  : myPaginator,
            usersDataSource : usersDataSource,
            usersDataTable  : usersDataTable
        };

        // Integrate with Browser History Manager
        var History = YAHOO.util.History;

        // Define a custom function to route sorting through the Browser History Manager
        var handleSorting = function (oColumn) {
            // Calculate next sort direction for given Column
            var sDir = this.getColumnSortDir(oColumn);

            // The next state will reflect the new sort values
            // while preserving existing pagination rows-per-page
            // As a best practice, a new sort will reset to page 0
            var newState = generateRequest(0, oColumn.key, sDir, this.get("paginator").getRowsPerPage());

            // Pass the state along to the Browser History Manager
            History.navigate("userTable", newState);
        };
        usersDataTable.sortColumn = handleSorting;

        // Define a custom function to route pagination through the Browser History Manager
        var handlePagination = function (state) {
            // The next state will reflect the new pagination values
            // while preserving existing sort values
            // Note that the sort direction needs to be converted from DataTable format to server value
            var sortedBy  = this.get("sortedBy"),
                newState = generateRequest(
                    state.recordOffset, sortedBy.key, sortedBy.dir, state.rowsPerPage
                );

            // Pass the state along to the Browser History Manager
            History.navigate("userTable", newState);
        };

        // First we must unhook the built-in mechanism...
        myPaginator.unsubscribe("changeRequest", usersDataTable.onPaginatorChangeRequest);
        // ...then we hook up our custom function
        myPaginator.subscribe("changeRequest", handlePagination, usersDataTable, true);

        // Update totalRecords on the fly with values from server
        usersDataTable.doBeforeLoadData = function (oRequest, oResponse, oPayload) {
            var meta = oResponse.meta;
            oPayload.totalRecords = meta.totalRecords || oPayload.totalRecords;
            oPayload.pagination = {
                rowsPerPage:meta.paginationRowsPerPage || number_per_page_default,
                recordOffset:meta.paginationRecordOffset || 0
            };
            if(oPayload.totalRecords==undefined){
                oPayload.totalRecords=0;
            }
            oPayload.sortedBy = {
                key: meta.sortKey || "id",
                dir: (meta.sortDir) ? "yui-dt-" + meta.sortDir : "yui-dt-asc" // Convert from server value to DataTable format
            };
            return true;
        };

        var generateRequest = function (startIndex,sortKey,dir,results) {
            var source = encodeURIComponent(Dom.get("source").value);
            var username = encodeURIComponent(Dom.get("username").value);
            var fullName = encodeURIComponent(Dom.get("fullName").value);
            var gender = encodeURIComponent(Dom.get("gender").value);
            var age = encodeURIComponent(Dom.get("age").value);
            var email = encodeURIComponent(Dom.get("email").value);
            var mobile = encodeURIComponent(Dom.get("mobile").value);
            var phone = encodeURIComponent(Dom.get("phone").value);
            var deviceNumber = encodeURIComponent(Dom.get("deviceNumber").value);
            var deviceModel = encodeURIComponent(Dom.get("deviceModel").value);
            var enabled = 1;
            var accountExpired = 0;
            var accountLocked =  0;
            var credentialsExpired =  0;
            startIndex = startIndex || 0;
            sortKey   = sortKey || "id";
            dir   = (dir) ? dir.substring(7) : "desc"; // Converts from DataTable format "yui-dt-[dir]" to server value "[dir]"
            results   = results || number_per_page_default;
            return  "sort=" + sortKey + "&dir=" + dir +
                "&start_index=" + startIndex + "&num_per_page=" + results  + "&source=" + source + "&username=" + username + "&fullName=" + fullName +
                "&gender=" + gender + "&age=" + age + "&email=" + email + "&mobile=" + mobile + "&phone=" + phone + "&enabled=" + enabled +
                "&accountExpired=" + accountExpired + "&accountLocked=" + accountLocked + "&credentialsExpired=" + credentialsExpired +
                "&deviceNumber=" + deviceNumber  + "&deviceModel=" + deviceModel  + "&time=" + new Date().getTime();
        };

        // Called by Browser History Manager to trigger a new state
        var handleHistoryNavigation = function (request) {
            //show the "loading" message.
            usersDataTable.getTbodyEl().style.display = "none";
            usersDataTable.showTableMessage(messages["js.loading"]);

            // Sends a new request to the DataSource
            usersDataSource.sendRequest(request, {
                success:function () {
                    checkUsersAll_btn.set("checked", false); //uncheck all.
                    usersDataTable.getTbodyEl().style.display = "";
                    usersDataTable.hideTableMessage();
                    usersDataTable.onDataReturnSetRows.apply(this, arguments);
                },
                failure:function () {
                    checkUsersAll_btn.set("checked", false); //uncheck all.
                    usersDataTable.getTbodyEl().style.display = "";
                    usersDataTable.hideTableMessage(YAHOO.widget.DataTable.MSG_ERROR);
                    usersDataTable.onDataReturnSetRows.apply(this, arguments);
                },
                scope:usersDataTable,
                argument:{} // Pass in container for population at runtime via doBeforeLoadData
            });
        };

        // Calculate the first request
        var initialRequest = History.getBookmarkedState("userTable") || // Passed in via URL
            generateRequest(); // Get default values

        // Register the module
        History.register("userTable", initialRequest, handleHistoryNavigation);

        // Render the first view
        History.onReady(function () {
            // Current state after BHM is initialized is the source of truth for what state to render
            var currentState = History.getCurrentState("userTable");
            handleHistoryNavigation(currentState);
        });

        var renderPage = function () {
            var currentState = History.getCurrentState("userTable") || generateRequest();
            handleHistoryNavigation(currentState);
        };

        var searchPage = function () {
            var currentState =  generateRequest();
            handleHistoryNavigation(currentState);
        };

        // Initialize the Browser History Manager.
        YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");

        usersDataTable.subscribe('cellClickEvent', function (ev) {
            var target = YAHOO.util.Event.getTarget(ev);
            var column = this.getColumn(target);
            var record = this.getRecord(target);
           if (column.action == 'view') {
               //show user cards info.
               window.location.href = "/admin/ozing/user/cards?id=" + record.getData("id");
           }else if(column.action=="oauth"){
                window.open ('/admin/user/token?id=' + record.getData("id"),
                       '生成用户OauthToken','height=320,width=480,top=0,left=0,toolbar=no,menubar=no,scrollbars=yes, resizable=yes,location=no, status=no');
           }
        });

        var refreshUserThread = function (p_oEvent) {
            searchPage();
        };

        //button.
        var refreshUsersThread_btn = new YAHOO.widget.Button("refreshUsersThread", { onclick:{ fn:refreshUserThread } });
        var checkUsersAll_btn = new YAHOO.widget.Button("selectUsersAll", { label:messages["select.all"], checked:false });
        var query_btn = new YAHOO.widget.Button("query_users_btn", {label:messages["button.search"],onclick:{ fn:searchPage } });

        usersDataTable.subscribe('checkboxClickEvent', function (oArgs) {
            var currentPageUrl = History.getCurrentState("userTable")||generateRequest();
            var start_index = parseInt(getRequestValueFromURL(currentPageUrl, "start_index"));
            var elCheckbox = oArgs.target;
            var newValue = elCheckbox.checked;
            var record = this.getRecord(elCheckbox);
            var column = this.getColumn(elCheckbox);
            record.setData(column.key, newValue);

            var allChecked = true;
            var oRS = usersDataTable.getRecordSet();
            for (var i = start_index; i < oRS.getLength(); i++) {
                var oRec = oRS.getRecord(i);
                if (!oRec.getData('Select')) {
                    allChecked = false;
                    break;
                }
            }
            checkUsersAll_btn.set("checked", allChecked);
            if (newValue) {
                this.selectRow(record);
            } else {
                this.unselectRow(record);
            }
            if (usersDataTable.getSelectedRows().length > 0) {
                //tokenUsersThread_btn.set("disabled", false);
            } else {
                //tokenUsersThread_btn.set("disabled", true);
            }
            return false;
        });

        checkUsersAll_btn.on("click", function (e) {
            var currentPageUrl = History.getCurrentState("userTable")||generateRequest();
            var start_index = parseInt(getRequestValueFromURL(currentPageUrl, "start_index"));
            var check = checkUsersAll_btn.get("checked");
            var oRS = usersDataTable.getRecordSet();
            for (var i = start_index; i < oRS.getLength(); i++) {
                var oRec = oRS.getRecord(i);
                oRec.setData('Select', check);
                if (check) {
                    usersDataTable.selectRow(oRec);
                } else {
                    usersDataTable.unselectRow(oRec);
                }
            }
            usersDataTable.render();
            if (usersDataTable.getSelectedRows().length > 0) {
               // tokenUsersThread_btn.set("disabled", false);
            } else {
               // tokenUsersThread_btn.set("disabled", true);
            }
        });

        return {
            ds:usersDataSource,
            dt:usersDataTable
        };

    }();
});
